﻿using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace LogikBug.ModularMvc
{
	public class ModuleControllerFactory : DefaultControllerFactory
	{
		#region Fields

		private readonly IDependencyResolver _locator;

		#endregion

		#region Constructors

		public ModuleControllerFactory()
		{
			_locator = DependencyResolver.Current;
		}

		public ModuleControllerFactory(IDependencyResolver locator)
		{
			_locator = locator;
		}

		#endregion

		#region Methods

		protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
		{
			try
			{
				var instance = _locator.GetInstance(controllerType);

				if (instance == null)
				{
					instance = base.GetControllerInstance(requestContext, controllerType);
				}

				return (IController)instance;
			}
			catch (Exception)
			{
				return base.GetControllerInstance(requestContext, controllerType);
			}
		}

		#endregion
	}
}
